/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.attachment.controller  
 */
package com.apache.attachment.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.LoggerVo;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.attachment.entity.AttachmentRegister;
import com.apache.attachment.entity.AttachmentStore;
import com.apache.attachment.manager.AttachmentRegisterManager;
import com.apache.attachment.manager.AttachmentStoreManager;
import com.apache.attachment.mommon.AttachmentConfig;
import com.apache.attachment.mommon.BeanUtil;
import com.apache.attachment.mommon.FileUtil;
import com.apache.attachment.mommon.ImageUtil;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.passport.common.PassportHelper;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;

/**
 * description:  
 * @author mhguo 创建时间：2015-5-20  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("/attachment/store/")
public class AttachmentStoreAction extends PlatFromAction<AttachmentStore> {

	/**
	 * 附件信息管理的Service
	 */
	@Autowired
	AttachmentStoreManager attachmentStoreManager;

	/**
	 * 附件库注册管理的Service
	 */
	@Autowired
	AttachmentRegisterManager attachmentRegisterManager;

	/**
	 * 
	 * 跳转到列表页面 
	 */
	@RequestMapping({ "list.action" })
	public ModelAndView list(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(LIST);
		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}

		//实体注册信息检查
		AttachmentRegister ar = getRegister(objType);
		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {//图片
				view.addObject("attaSort", "1");
				view = new ModelAndView("attachment/mvc/pic-store-list");
			} else {//文件
				view.addObject("attaSort", "0");
			}
		} else {
			view = new ModelAndView("error/error");
			view.addObject("errors", "实体未注册!");
			return view;
		}

		view.addObject("objId", objId);
		view.addObject("objType", objType);
		return view;
	}

	/**
	 *  跳转到上传页面  
	 */
	@Token(save = true)
	@RequestMapping(value = { "add.action" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	protected ModelAndView add(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(this.ADD);
		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}

		//实体注册信息检查
		AttachmentRegister ar = getRegister(objType);
		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {
				view = new ModelAndView("attachment/mvc/pic-store-save");
			}
		} else {
			view = new ModelAndView("error/error");
			view.addObject("errors", "实体未注册!");
			return view;
		}

		AttachmentStore attaStore = new AttachmentStore();
		attaStore.setObjId(objId);
		attaStore.setObjType(objType);
		view.addObject("attaStore", attaStore);
		return view;
	}

	/**
	 * 初始化信息，跳转到修改页面  
	 */
	@Token(save = true)
	@RequestMapping("edit.action")
	public ModelAndView edit(HttpServletRequest request, String id) {
		ModelAndView view = new ModelAndView(EDIT);

		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objType)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}

		//实体注册信息检查
		AttachmentRegister ar = getRegister(objType);
		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {
				view = new ModelAndView("attachment/mvc/pic-store-save");
			}
		} else {
			view = new ModelAndView("error/error");
			view.addObject("errors", "实体未注册!");
			return view;
		}

		AttachmentStore attaStore = null;
		ParamsVo vo = new ParamsVo();
		vo.setInfoId(id);
		vo.setObj(null);
		attaStore = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		view.addObject("attaStore", attaStore);
		return view;
	}

	/**
	 * 通过objType得到实体注册信息
	 */
	public AttachmentRegister getRegister(String objType) {
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);
		if (arList.size() > 0) {
			ar = arList.get(0);
		}
		return ar;
	}

	/**
	 * 上传附件
	 */
	@Token(remove = true)
	@RequestMapping(value = { "uploadAttachment.action" }, method = { RequestMethod.POST })
	public @ResponseBody
	ResultMsg uploadAttachment(@RequestParam("upload") CommonsMultipartFile upload, HttpServletRequest request,
			HttpServletResponse response, AttachmentStore attaStore) throws BusinessException {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			return getResultMsg(request, "缺少必要的参数，系统调用异常!");
		}

		//实体注册信息检查
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);
		if (arList.size() < 1) {
			return getResultMsg(request, "实体未注册!");
		} else {

			AttachmentRegister r = arList.get(0);

			LoggerVo loggerVo = new LoggerVo();
			ParamsVo<AttachmentStore> voSt = this.getParamsVo(request);
			String sid = attaStore.getSid();
			if (Validator.isNull(sid)) {//新增
				int attTotal = 0;
				int attListTotal = 0;

				attTotal = r.getPicTotalNum();//最大上传个数

				if (Validator.isEmpty(upload)) {
					return getResultMsg(request, "请选择要上传的附件!");
				}

				String uploadFileName = upload.getOriginalFilename();
				String nameEx = FileUtil.getInstance().getExtension(uploadFileName);//取得文件扩展名
				//附件类型校验
				String alt = StrUtil.doNull(r.getAlloweTypes()).toUpperCase();
				if (!alt.equals("*.*")) {
					if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
						return getResultMsg(request, "不允许的文件类型!");
					}
				}

				//根据objId和objType查询附件信息
				AttachmentStore as = new AttachmentStore();
				as.setObjId(objId);
				as.setObjType(objType);
				vo.setObj(as);
				List<AttachmentStore> attaStoreList = attachmentStoreManager.getList(vo);
				attListTotal = attaStoreList.size();

				if (attTotal <= attListTotal && attTotal > 0) {
					return getResultMsg(request, "您上传的附件已经超过预定设置上传个数:(" + attTotal + "个)!");
				} else if (attTotal < 0) {
					return getResultMsg(request, "预定设置上传个数不能为负数!");
				}

				if (upload.getSize() / 1024L > r.getMaxLength()) {
					return getResultMsg(request, "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
				}

				/*if (upload.getSize() / 1024L < 10) {
					return getResultMsg(request, "你的附件小于10KB,请处理后重新上传!");
				}*/

				String uploadContentType = upload.getContentType();
				logger.info(upload.getName() + "  " + uploadFileName + "  " + uploadContentType);
				//System.out.println(upload.getName() + "  " + uploadFileName + "  " + uploadContentType);

				String uploadPath;//附件上传目录的前一段
				String downloadUrl;//附件下载地址的前一段
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {//图片
					uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/pics/";
					downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/pics/";
				} else {//文件
					uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/atta/";
					downloadUrl = AttachmentConfig.getProp("/atta/");
				}
				if (StrUtil.isEmptyWithTrim(uploadPath)) {
					uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
				}

				//附件上传、下载目录的后一段
				String cacDir = "/" + objType + "/" + new SimpleDateFormat("yyyyMM").format(new Date()) + "/" + objId
						+ "/";
				String uplDir = uploadPath + cacDir;
				File s = new File(uplDir);
				if (!s.exists()) {
					FileUtil.getInstance().makDir(uplDir);//创建目录
				}

				String AttachmentId = String.valueOf(System.currentTimeMillis());
				String wrFileName = cacDir + AttachmentId + "." + nameEx;
				logger.info("-----------最终文件名：" + wrFileName);
				String wrMiddleFileName = "";
				String wrSmallFileName = "";

				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
					wrMiddleFileName = cacDir + AttachmentId + ".m." + nameEx;//中图
					logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
					wrSmallFileName = cacDir + AttachmentId + ".s." + nameEx;//小图
					logger.info("wrSmallFileName[{}]" + wrSmallFileName);
					try {
						FileUtil.getInstance().writeFile(upload, uploadPath + wrFileName);
						logger.info("-----------原图上传成功：" + wrFileName);
						FileUtil.getInstance().copy(new File(uploadPath + wrFileName),
								new File(uploadPath + wrSmallFileName));
						logger.info("-----------小图创建成功：" + wrSmallFileName);
						ImageUtil.getInstance().resize(uploadPath + wrSmallFileName,
								(r.getSmallWidth() == null) ? 0 : r.getSmallWidth(),
								(r.getSmallHeight() == null) ? 0 : r.getSmallHeight());
						logger.info("-----------小图缩放成功：" + wrFileName);
						FileUtil.getInstance().copy(new File(uploadPath + wrFileName),
								new File(uploadPath + wrMiddleFileName));
						logger.info("-----------中图创建成功：" + wrMiddleFileName);
						ImageUtil.getInstance().resize(uploadPath + wrMiddleFileName,
								(r.getMiddleWidth() == null) ? 0 : r.getMiddleWidth(),
								(r.getMiddleHeigth() == null) ? 0 : r.getMiddleHeigth());
						logger.info("-----------中图缩放成功：" + wrFileName);
						String wmf = StrUtil.doNull(r.getWatermarkFile());
						if (StrUtil.isNotEmptyWithTrim(wmf)) {
							ImageUtil.getInstance().pressImage(r.getWatermarkFile(), uploadPath + wrMiddleFileName,
									r.getWmX(), r.getWmY(), r.getWmFilter().floatValue());
							logger.info("-----------中图添加水印成功：" + wrFileName);
						}
					} catch (FileNotFoundException e) {
						logger.error(">>>>>>>>>图片未找到，上传失败!!!!!!" + e);
						return getResultMsg(request, "图片未找到，上传失败!");
					} catch (IOException e) {
						logger.error(">>>>>>>>>图片操作异常!!!!!!!!" + e);
						return getResultMsg(request, "图片操作异常!");
					}

				} else {
					try {
						FileUtil.getInstance().writeFile(upload, uploadPath + wrFileName);
						logger.info("-----------附件原图上传成功：" + wrFileName);
					} catch (FileNotFoundException e) {
						logger.error(">>>>>>>>>附件未找到，上传失败!!!!!!" + e);
						return getResultMsg(request, "附件未找到，上传失败!");
					} catch (IOException e) {
						logger.error(">>>>>>>>>附件操作异常!!!!!!!!" + e);
						return getResultMsg(request, "附件操作异常!");
					}

				}

				attaStore.setSid(AttachmentId);//附件信息id
				attaStore.setDownloadUrl(downloadUrl + cacDir);//下载地址(不包括附件名)
				attaStore.setAttachmentType(nameEx);//附件类型(文件后缀名)
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
				String nowDate = sdf.format(date);
				attaStore.setCreateTime(nowDate);
				//单点登录用户信息
				String tokenId = PassportHelper.getInstance().getCurrCookie(request);

				//session中已经存在用户登录对象，则从session中获取
				Object loginObj = request.getSession().getAttribute("loginUser");
				LoginUser loginUser = null;
				if (loginObj == null) {
					loginUser = PBOSSOTools.getLoginUserFromUserCenterSso(tokenId);
				} else {
					loginUser = PBOSSOTools.getLoginUser(request);
				}
				if (loginUser == null) {
					this.logger.info("AttachmentStoreAction中未获取到loginUser登录信息:" + loginUser);
				}
				attaStore.setCreateUserId(loginUser.getUserId());
				attaStore.setCreateUserRealname(loginUser.getUserCname());
				attaStore.setCreateSpaceEname(loginUser.getUserEname());
				attaStore.setServerid(loginUser.getDataDomain());
				attaStore.setAbsolutePath(uploadPath + cacDir);//附件绝对路径(不包括附件名)
				String mainPigFlag = request.getParameter("mainPicFlag");
				if (Validator.isNotNull(mainPigFlag))
					attaStore.setMainPicFlag(mainPigFlag);//是否为主图：(主图：1；非主图：0；)

				voSt.setObj(attaStore);
				sid = attachmentStoreManager.saveInfo(voSt);
				if (Validator.isNull(sid)) {
					return getResultMsg(request, "新增条目失败，请重试!");
				}

				//如果设置了图片主图参数，进行相应的操作
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())
						&& Validator.isNotNull(mainPigFlag)) {
					if ("1".equals(mainPigFlag.trim())) {
						setMainPicFlag(request, AttachmentId);//批量更新：主图mainPicFlag字段为1，其余均更新为0
					}
				}

			} else {

				voSt.setInfoId(sid);
				AttachmentStore attaStoreEntity = (AttachmentStore) attachmentStoreManager.getInfoById(voSt);

				//替换附件
				if (!upload.isEmpty()) {

					String uploadFileName = upload.getOriginalFilename();
					String nameEx = FileUtil.getInstance().getExtension(uploadFileName);//取得文件扩展名
					//附件类型校验
					String alt = StrUtil.doNull(r.getAlloweTypes()).toUpperCase();
					if (!alt.equals("*.*")) {
						if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
							return getResultMsg(request, "不允许的文件类型!");
						}
					}

					if (upload.getSize() / 1024L > r.getMaxLength()) {
						return getResultMsg(request, "你的附件大于 " + r.getMaxLength() + "KB,请处理后重新上传!");
					}

					/*if (upload.getSize() / 1024L < 10) {
						return getResultMsg(request, "你的附件小于10KB,请处理后重新上传!");
					}*/

					String attafileName = attaStoreEntity.getSid() + "." + attaStoreEntity.getAttachmentType();
					String uploadDir = getUploadDir(request, sid, attaStoreEntity);
					String uploadDirpro = uploadDir + attafileName;//原图上传地址

					//校验附件是否存在
					vo.setInfoId(sid);
					vo.setObj(null);
					AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
					if (null == as) {
						return rmsg = getResultMsg(request, "附件不存在或者已经删除！");
					}

					if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())) {
						String wrMiddleFileName = attaStoreEntity.getSid() + ".m."
								+ attaStoreEntity.getAttachmentType();
						logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
						String uploadDirm = uploadDir + wrMiddleFileName;//中图上传地址
						String wrSmallFileName = attaStoreEntity.getSid() + ".s." + attaStoreEntity.getAttachmentType();
						logger.info("wrSmallFileName[{}]" + wrSmallFileName);
						String uploadDirs = uploadDir + wrSmallFileName;//小图上传地址
						try {
							FileUtil.getInstance().writeFile(upload, uploadDirpro);
							logger.info("-----------原图上传成功：" + attafileName);
							FileUtil.getInstance().copy(new File(uploadDirpro), new File(uploadDirs));
							logger.info("-----------小图创建成功：" + wrSmallFileName);
							ImageUtil.getInstance().resize(uploadDirs,
									(r.getSmallWidth() == null) ? 0 : r.getSmallWidth(),
									(r.getSmallHeight() == null) ? 0 : r.getSmallHeight());
							logger.info("-----------小图缩放成功：" + attafileName);
							FileUtil.getInstance().copy(new File(uploadDirpro), new File(uploadDirm));
							logger.info("-----------中图创建成功：" + wrMiddleFileName);
							ImageUtil.getInstance().resize(uploadDirm,
									(r.getMiddleWidth() == null) ? 0 : r.getMiddleWidth(),
									(r.getMiddleHeigth() == null) ? 0 : r.getMiddleHeigth());
							logger.info("-----------中图缩放成功：" + attafileName);
							String wmf = StrUtil.doNull(r.getWatermarkFile());
							if (StrUtil.isNotEmptyWithTrim(wmf)) {
								ImageUtil.getInstance().pressImage(r.getWatermarkFile(), uploadDirm, r.getWmX(),
										r.getWmY(), r.getWmFilter().floatValue());
								logger.info("-----------中图添加水印成功：" + attafileName);
							}
						} catch (FileNotFoundException e) {
							logger.error(">>>>>>>>>图片未找到，上传失败!!!!!!" + e);
							return getResultMsg(request, "图片未找到，上传失败!");
						} catch (IOException e) {
							logger.error(">>>>>>>>>图片操作异常!!!!!!!!" + e);
							return getResultMsg(request, "图片操作异常!");
						}

					} else {
						try {
							FileUtil.getInstance().writeFile(upload, uploadDirpro);
						} catch (FileNotFoundException e) {
							logger.error(">>>>>>>>>附件未找到，替换附件失败!!!!!!" + e);
							return getResultMsg(request, "附件未找到，替换附件失败!");
						} catch (IOException e) {
							logger.error(">>>>>>>>>附件操作异常!!!!!!!!" + e);
							return getResultMsg(request, "附件操作异常!");
						}
					}

				}

				BeanUtil.copy(attaStore, attaStoreEntity);
				voSt.setInfoId(null);
				voSt.setObj(attaStoreEntity);
				boolean mark = attachmentStoreManager.editInfo(voSt);
				if (!mark) {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
				}

				//如果设置了图片主图参数，进行相应的操作
				if (Validator.isNotNull(r.getAttaSort()) && "1".equals(r.getAttaSort().trim())
						&& Validator.isNotNull(attaStoreEntity.getMainPicFlag())) {
					if ("1".equals(attaStoreEntity.getMainPicFlag().trim())) {
						setMainPicFlag(request, attaStoreEntity.getSid());
					}
				}

			}

		}
		return rmsg;
	}

	/**
	 * description:获得上传目录  
	 * @author mhguo 
	 * @update 2015-5-28
	 */
	public String getUploadDir(HttpServletRequest request, String id, AttachmentStore as) {
		String uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY");
		String downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL");
		if (StrUtil.isEmptyWithTrim(uploadPath)) {
			uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
		}
		//java中使用正则获得路径
		String regEx = downloadUrl;
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(as.getDownloadUrl());
		String filePath_ = mat.replaceAll("");
		String attaFilePath = filePath_.substring(1, filePath_.lastIndexOf("/"));
		String uploadDir = uploadPath + File.separator + attaFilePath + File.separator;
		return uploadDir;
	}

	ResultMsg getResultMsg(HttpServletRequest request, String msg) {
		request.getSession().setAttribute("formToken", request.getAttribute("formToken"));
		ResultMsg rmsg = new ResultMsg("F", msg);
		return rmsg;
	}

	/**
	 * 删除附件及信息  
	 */
	@RequestMapping("del.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		if (Validator.isNull(id)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数!");
			return rmsg;
		}

		//校验附件是否存在
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
		vo.setInfoId(id);
		AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("附件不存在或者已经删除！");
		}

		String attafileName = as.getSid() + "." + as.getAttachmentType();
		String uploadDir = getUploadDir(request, id, as);
		String uploadDirpro = uploadDir + attafileName;

		boolean mark = attachmentStoreManager.deleteInfo(vo);
		if (!mark) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败！");
			return rmsg;
		}

		String attaSort = request.getParameter("attaSort");
		if (Validator.isNotNull(attaSort) && "1".equals(attaSort.trim())) {
			String wrMiddleFileName = as.getSid() + ".m." + as.getAttachmentType();//中图名
			logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
			String uploadDirm = uploadDir + wrMiddleFileName;//中图上传地址
			String wrSmallFileName = as.getSid() + ".s." + as.getAttachmentType();//小图名
			logger.info("wrSmallFileName[{}]" + wrSmallFileName);
			String uploadDirs = uploadDir + wrSmallFileName;//小图上传地址

			File file = new File(uploadDirpro);
			File filem = new File(uploadDirm);
			File files = new File(uploadDirs);

			if (file.exists() && filem.exists() && files.exists()) {
				boolean ob = file.delete();
				boolean obm = filem.delete();
				boolean obs = files.delete();
				if (ob & obm && obs) {
					rmsg.setFlag("T");
					rmsg.setMsg("操作成功！");
				} else {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
					return rmsg;
				}
			} else {
				rmsg.setFlag("T");
				//rmsg.setMsg("图片信息已删除，但没有找到图片！");
				rmsg.setMsg("图片信息已删除！");
			}
		} else {
			File file = new File(uploadDirpro);
			if (file.exists()) {
				boolean ob = file.delete();
				if (ob) {
					rmsg.setFlag("T");
					rmsg.setMsg("操作成功！");
				} else {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
					return rmsg;
				}
			} else {
				rmsg.setFlag("T");
				//rmsg.setMsg("附件信息已删除，但没有找到附件！");
				rmsg.setMsg("附件信息已删除！");
			}

		}

		return rmsg;
	}

	/**
	 * 设置主题
	 */
	@RequestMapping("setMainPicFlag.action")
	@ResponseBody
	public ResultMsg setMainPicFlag(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示

		if (Validator.isNull(id) || Validator.isNull(objId) || Validator.isNull(objType)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		AttachmentStore as;
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();

		vo.setInfoId(id);
		as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);

		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("图片不存在或者已经删除！");
			return rmsg;
		}

		LoggerVo loggerVo = new LoggerVo();
		vo = this.getParamsVo(request);

		//根据objId、objType查询附件信息
		AttachmentStore asp = new AttachmentStore();
		asp.setObjType(objType);
		asp.setObjId(objId);
		vo.setInfoId(null);
		vo.setObj(asp);
		List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
		for (int i = 0; i < asList.size(); i++) {
			if (id.trim().equals(asList.get(i).getSid().trim())) {
				asList.get(i).setMainPicFlag("1");//主图
			} else {
				asList.get(i).setMainPicFlag("0");//非主图
			}

			vo.setObj(asList.get(i));
			boolean edrs = attachmentStoreManager.editInfo(vo);
			if (!edrs) {
				rmsg.setFlag("F");
				rmsg.setMsg("操作失败！");
				return rmsg;
			}
		}

		return rmsg;
	}

	/**
	 * 访问ip验证
	 */
	private boolean checkIp(String userIp, String defineIp) {
		String uIp = StrUtil.doNull(userIp);
		String defIp = StrUtil.doNull(defineIp);
		if (StrUtil.isEmptyWithTrim(defIp)) {
			return true;
		}
		if (defIp.indexOf(uIp) != -1) {
			return true;
		}
		return false;
	}

	/**
	 * 查询所有附件  
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("list!data.action")
	protected ModelAndView data(HttpServletRequest request, String page, String rows) {
		ModelAndView view = null;
		ParamsVo vo = new ParamsVo();

		String objId = request.getParameter("objId");//实体id
		String objType = request.getParameter("objType");//实体英文注册标示
		if (Validator.isNull(objId) || Validator.isNull(objType)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}

		AttachmentRegister ar = getRegister(objType);
		if (!Validator.isEmpty(ar)) {
			if ("1".equals(ar.getAttaSort().trim())) {
				view = new ModelAndView("attachment/mvc/pic-store-listresult");
			} else {
				view = new ModelAndView("attachment/mvc/attachment-store-listresult");
			}
		} else {
			view = new ModelAndView("error/error");
			view.addObject("errors", "实体未注册!");
			return view;
		}

		//权限检查
		String ip = StrUtil.doNull(ar.getIpAddress());

		if (StrUtil.isNotEmptyWithTrim(ip)) {
			boolean ipflag = checkIp(request.getRemoteAddr(), ar.getIpAddress());
			if (!ipflag) {
				view = new ModelAndView("error/error");
				view.addObject("errors", "无访问权限！");
				return view;
			}
		}

		AttachmentStore as = new AttachmentStore();
		as.setObjId(objId);
		as.setObjType(objType);
		vo.setObj(as);
		List<AttachmentStore> attaStoreList = attachmentStoreManager.getList(vo);
		view.addObject("attaStoreList", attaStoreList);

		return view;
	}

	@Override
	protected BaseManager<AttachmentStore> getBaseManager() {
		return attachmentStoreManager;
	}

	@Override
	protected String getPrefix() {
		return "attachment/mvc/attachment-store-";
	}

}
